﻿using SpiderPlatform.Dao;
using SpiderPlatform.Entity;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace SpiderPlatform.Detail
{
    public class RanchDetailService
    {
        string apiService = "https://api.freshop.com/1/products";
        string token = string.Empty;
        string app_key = "99_ranch_market";
        // string fields = "id,identifier,reference_id,reference_ids,upc,name,store_id,department_id,size,cover_image,price,sale_price,sale_start_date,sale_finish_date,price_disclaimer,sale_price_disclaimer,is_favorite,relevance,popularity,shopper_walkpath,fulfillment_walkpath,quantity_step,quantity_minimum,quantity_initial,quantity_label,quantity_label_singular,varieties,quantity_size_ratio_description,status,status_id,sale_configuration_type_id,fulfillment_type_id,fulfillment_type_ids,other_attributes,clippable_offer,slot_message,call_out,has_featured_offer,tax_class_label,promotion_text,sale_offer,store_card_required,average_rating,review_count,offered_together,sequence";
        string fields = "id,upc,name,store_id,department_id,size,price,sale_price,description,identifier,images,quantity_on_hand";
        ItemDao itemDao = new ItemDao();
        public void doWork() {
            var list = itemDao.QueryChannelItemRealTime(3);
            GetToken();
            List<Task> taskList = new List<Task>();
            List<Task> taskList2 = new List<Task>();
            foreach (var item in list)
            {          
                taskList.Add(Task.Factory.StartNew(async ()=> {
                    Logger.Info("process "+item.channel_sku);
                    var t2 = GetProductAsync(item.channel_sku);
                    taskList2.Add(t2);
                    var data =await t2;
                    item.is_instock = data.quantity_on_hand;
                    item.score = 0;
                    item.reviews = 0;
                    item.price = decimal.Parse(data.price.TrimStart('$'));
                }));                  
            }
            Task.WaitAll(taskList.ToArray());
            Task.WaitAll(taskList2.ToArray());
            Logger.Info("...load data done...");
            itemDao.UpdateChannelItemRealTime(list);
            Logger.Info("...all done...");
        }
        private string GetToken()
        {           
            RanchToken token = new RanchToken();
            Logger.Info("get token success...");           
            HttpClient client = new HttpClient();
            var res = client.GetAsync($"https://api.freshop.com/2/sessions/8ee2afde191e8b8405d205ba99ff9ab4?app_key={app_key}").Result;
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                token = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchToken>(data);
            }
            return token.token;
        }
        private async Task<RanchProduct> GetProductAsync(string channelSku)
        {
            RanchProduct result = new RanchProduct();
            HttpClient client = new HttpClient();          
            var res = await client.GetAsync($"{apiService}/{channelSku}?app_key=99_ranch_market&render_id=1563600168242&store_id=3122&token={token}");
            if (res.StatusCode == System.Net.HttpStatusCode.OK)
            {
                string data = res.Content.ReadAsStringAsync().Result;
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<RanchProduct>(data);
            }
            return result;
        }
    }
}
